<?php
class omeanalysts_mdl_ome_orderreplace extends dbeav_model{

    //var $has_export_cnf = true;

    var $export_name = 'OMS订单替换物料报表';

    public function table_name($real=false){
        $table_name = 'ome_delivery';
        if($real){
            return kernel::database()->prefix.$table_name;
        }else{
            return $table_name;
        }
    }

    public function count($filter=null){

        $where = $this->_filter($filter); 

        $sql = "SELECT count(*) as _count  FROM sdb_ome_orders os
                inner join sdb_ome_shop f on os.shop_id=f.shop_id
                inner JOIN sdb_ome_order_itemsRep rep on os.order_id=rep.order_id
                inner join sdb_ome_order_items items on rep.newitem_id=items.item_id
                where 1=1 and ".$where." ";

        $row = $this->db->select($sql);
        return intval($row[0]['_count']);
    }

    public function getlist($cols='*', $filter=array(), $offset=0, $limit=-1, $orderType=null){
  

        if(!$filter['time_from'] && !$filter['time_to']){
            return false;
        }else{

            $where = $this->_filter($filter);
            $sql = "SELECT os.order_bn,os.total_amount money,os.download_time createtime,os.shop_id,f.`name` shop_name,f.AXCustomer,f.customername,rep.bn ,rep.nums,items.bn replace_bn,items.nums replace_number,rep.op_id,rep.op_name operator,rep.op_time replacetime FROM sdb_ome_orders os
            inner join sdb_ome_shop f on os.shop_id=f.shop_id
            inner JOIN sdb_ome_order_itemsRep rep on os.order_id=rep.order_id
            inner join sdb_ome_order_items items on rep.newitem_id=items.item_id
            where 1=1 and ".$where." ";
            $rows = $this->db->selectLimit($sql,$limit,$offset);
            return $rows;
        }
        
    }
    
    public function searchOptions(){
        $parentOptions = parent::searchOptions();
        $childOptions = array(
            'order_bn'=>app::get('base')->_('订单号'),
        );
        return $Options = array_merge($parentOptions,$childOptions);
    }

    public function _filter($filter,$tableAlias=null,$baseWhere=null){
       
        $where = array(1);
       if(empty($filter['time_from']))
        {
          $where[]=' 1=2 ';
        }
        if(isset($filter['time_from']) && $filter['time_from']){
            $where[] = ' os.download_time >='.strtotime($filter['time_from']);
        }
        if(isset($filter['time_to']) && $filter['time_to']){
            $where[] = ' os.download_time <'.(strtotime($filter['time_to'])+86399);
        }
         
        if(isset($filter['shop_id'])   && $filter['shop_id']){
            $where[] = ' f.shop_id  =\''.addslashes($filter['shop_id']).'\'';
        }
        if(!$filter['shop_id'] && $filter['shop_ids']){
            $where[] = ' f.shop_id IN (\''.implode('\',\'', $filter['shop_ids']).'\')';
        }
        unset($filter['shop_id']);

        if(isset($filter['AXCustomer']) && $filter['AXCustomer']){
            $where[]= ' f.AXCustomer  =\''.addslashes($filter['AXCustomer']).'\'';

        }  
        if(isset($filter['axcustomercode']) && $filter['axcustomercode']){
            $where[]= ' f.AXCustomer  =\''.addslashes($filter['axcustomercode']).'\'';

        }
        if(isset($filter['bn']) && $filter['bn']){
            $where[] = ' rep.bn =\''.addslashes($filter['bn']).'\'';
        }
        if(isset($filter['rep_bn']) && $filter['rep_bn']){
            $where[] = ' items.bn =\''.addslashes($filter['rep_bn']).'\'';
        }
        if(isset($filter['order_bn']) && $filter['order_bn']){
            $where[] = ' os.order_bn =\''.addslashes($filter['order_bn']).'\'';
        }
        return implode($where,' AND ');
    }
    //订单号、店铺、时间、物料、数量、替换物料、替换数量、金额、替换人、操作时间
    public function get_schema(){
        $schema = array (
            'columns' => array (
                'createtime' =>
                array (
                  'type' => 'time',
                  'label' => '订单下载日期',
                  'comment' => '订单下载日期',
                  'editable' => false,
                  'in_list' => true,
                ),
                'order_bn' =>
                array (
                  'type' => 'varchar(255)',
                  'label' => '订单号',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '200',
                ),
                'shop_name' =>
                array (
                  'type' => 'varchar(255)',
                  'label' => '店铺',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '200',
                ),
                'AXCustomer' =>
                array (
                  'type' => 'varchar(255)',
                  'label' => '客户',
                  'editable' => false,
                  'searchtype' => 'has',
                  'filtertype' => 'normal',
                  'filterdefault' => true,
                  'in_list' => true,
                  'default_in_list' => true,
                  'is_title' => true,
                  'width' => '100',
                ),
                'bn' =>
                array (
                  'type' => 'varchar(30)',
                  'label' => '原物料编码',
                  'editable' => false,
                  'is_title' => true,
                  'width' => '100',
                ),
                'nums' =>
                array (
                  'type' => 'number',
                  'label' => '原物料数量',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                  'width' => '100',
                ),
                'replace_bn' =>
                array (
                  'type' => 'varchar(30)',
                  'label' => '替换物料编码',
                  'editable' => false,
                  'is_title' => true,
                  'width' => '100',
                ),
                'replace_number' =>
                array (
                  'type' => 'number',
                  'label' => '替换物料数量',
                  'required' => true,
                  'default' => 0,
                  'editable' => false,
                  'width' => '100',
                ),
                'operator'=>
                array(
                    'type'=>'varchar(50)',
                    'label'=>'替换人',
                    'in_list' => true,
                    'default_in_list' => true,
                  'width' => '150',
                ),
                'replacetime' =>
                array (
                  'type' => 'time',
                  'label' => '替换时间',
                  'comment' => '替换时间',
                  'editable' => false,
                  'in_list' => true,
                  'width' => '100',
                ),
                'money' =>
                array (
                  'type' => 'money',
                  'label' => '订单总额',
                  'comment' => '订单总额',
                  'editable' => false,
                  'filtertype' => 'normal',
                  'in_list' => true,
                  'width' => '70',
                ),
            ),
            'idColumn' => 'name',
            'in_list' => array (
                0 => 'createtime',
                1 => 'order_bn',
                2 => 'shop_name',
                3 => 'AXCustomer',
                4 => 'bn',
                5 => 'nums',
                6 => 'replace_bn',
                7 => 'replace_number',
                8 => 'operator',
                9 => 'replacetime',
                10 => 'money',      
            ),
            'default_in_list' => array (
                0 => 'createtime',
                1 => 'order_bn',
                2 => 'shop_name',
                3 => 'AXCustomer',
                4 => 'bn',
                5 => 'nums',
                6 => 'replace_bn',
                7 => 'replace_number',
                8 => 'operator',
                9 => 'replacetime',
                10 => 'money',
            ),
        );
        return $schema;
    }

    /**
     * 获得日志类型(non-PHPdoc)
     * @see dbeav_model::getLogType()
     */
    public function getLogType($logParams) {
        $type = $logParams['type'];
        $logType = 'none';
        if ($type == 'export') {
            $logType = $this->exportLogType($logParams);
        }
        elseif ($type == 'import') {
            $logType = $this->importLogType($logParams);
        }
        return $logType;
    }
    /**
     * 导出日志类型
     * @param Array $logParams 日志参数
     */
    public function exportLogType($logParams) {
        $params = $logParams['params'];
        $type = 'report';
        if ($logParams['app'] == 'omeanalysts' && $logParams['ctl'] == 'ome_delivery') {
            $type .= '_purchaseReport_expressAnalysis';
        }
        $type .= '_export';
        return $type;
    }
    /**
     * 导入操作日志类型
     * @param Array $logParams 日志参数
     */
    public function importLogType($logParams) {
        $params = $logParams['params'];
        $type = 'report';
        if ($logParams['app'] == 'omeanalysts' && $logParams['ctl'] == 'ome_delivery') {
            $type .= '_purchaseReport_expressAnalysis';
        }
        $type .= '_import';
        return $type;
    }

    function io_title( $filter, $ioType='csv' )
    {
        switch( $filter ){
            case 'delivery':
                $this->oSchema['csv'][$filter] = array(
                    '*:订单号' => 'order_bn',
                    '*:订单下载日期' => 'createtime',
                    '*:来源店铺' => 'shop_name',
                    '*:客户' => 'AXCustomer',    
                    '*:订单总额' => 'money',    
                    '*:原物料编码' => 'bn',  
                    '*:原物料数量' => 'nums',   
                    '*:替换物料编码' => 'replace_bn',  
                    '*:替换物料量' => 'replace_number',   
                    '*:替换人' => 'operator',
                    '*:替换时间' => 'replacetime',
                );
                break;
        }
        $this->ioTitle[$ioType][$filter] = array_keys( $this->oSchema[$ioType][$filter] );
        return $this->ioTitle[$ioType][$filter];
    }

    //根据查询条件获取导出数据
    public function getExportDataByCustom($fields, $filter, $has_detail, $curr_sheet, $start, $end){
          //根据选择的字段定义导出的第一行标题
          if($curr_sheet == 1){

              $title = array();
              foreach($this->io_title('delivery') as $k => $v ){
                  $title[] = mb_convert_encoding($v, 'GBK', 'UTF-8');
              }

              $data['content']['main'][0] = '"'.implode('","',$title).'"';
          }

          $where = $this->_filter($filter);
         
            $sql = "SELECT os.order_bn,FROM_UNIXTIME(os.download_time, '%Y-%m-%d %H:%i:%S') createtime,f.`name` shop_name,f.AXCustomer,os.total_amount money,rep.bn ,rep.nums,items.bn replace_bn,items.nums replace_number,rep.op_name operator,FROM_UNIXTIME(rep.op_time , '%Y-%m-%d %H:%i:%S')replacetime 
            FROM sdb_ome_orders os
            inner join sdb_ome_shop f on os.shop_id=f.shop_id
            inner JOIN sdb_ome_order_itemsRep rep on os.order_id=rep.order_id
            inner join sdb_ome_order_items items on rep.newitem_id=items.item_id 
            where 1=1 and ".$where;
            $rows = $this->db->selectLimit($sql,$end,$start); 
        
            error_log(date('Y-m-d H:i:s').'循环次数：【'.json_encode($rows).'】\r\n', 3, PUBLIC_DIR . '/autoorderreplace' . date('Y-m-d') . '.log');

            foreach ($rows as $k => $aFilter) {
                $exptmp_data = array();
                foreach ($aFilter as $col => $val) {
                    $aFilter[$col] = mb_convert_encoding($aFilter[$col], 'GBK', 'UTF-8');
                    $exptmp_data[] = $aFilter[$col];
                }
                $data['content']['main'][] = implode(',', $exptmp_data);
            }
            return $data;
        
    }
}
